<template>
  <div class="system-user-dialog-container">
    <el-dialog :title="state.dialog.title" v-model="state.dialog.isShowDialog" width="1000px">
      <el-form ref="appsDialogFormRef" :model="state.ruleForm" :rules="rules" size="default" label-width="auto">
        <el-row :gutter="35">
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
            <el-form-item label="应用logo" prop="appLogo">
              <el-input type="hidden" v-model="state.ruleForm.appLogo" placeholder="请输入" clearable></el-input>
              <el-upload
                  v-model:file-list="fileList"
                  list-type="picture-card"
                  action="https://www.slkjyun.cn/api/admin/file/upload"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload"
                  :on-preview="handlePictureCardPreview"
                  :on-remove="handleRemove"
              >
                <el-icon>
                  <Plus/>
                </el-icon>
              </el-upload>

            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="35">
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
            <el-form-item label="应用名称" prop="appName">
              <el-input v-model="state.ruleForm.appName"
                        placeholder="请输入应用名称"
                        clearable>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
            <el-form-item label="应用简称" prop="appShortName">
              <el-input v-model="state.ruleForm.appShortName"
                        placeholder="请输入应用简称"
                        clearable>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="35">
          <el-col :span="24" class="mb20">
            <el-form-item label="应用描述" prop="appShortDesc">
              <el-input type="textarea"
                        v-model="state.ruleForm.appShortDesc"
                        placeholder="请输入应用描述"
                        clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="35">
          <el-col :span="24" class="mb20">
<!--            check-strictly-->
            <el-form-item label="所属学校(含教育局相关机构)" prop="orgId">
              <el-tree-select
                  v-model="state.ruleForm.orgId"
                  :data="state.sysOrgData"
                  :render-after-expand="false"
                  style="width: 500px"
                  filterable
                  show-all-levels
                  multiple
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="35">
          <el-col :span="24" class="mb20">
            <el-form-item label="所属地区" prop="orgId">
<!--              check-strictly-->
              <el-tree-select
                  v-model="state.ruleForm.areaOrgIds"
                  :data="state.areaOrgData"
                  :render-after-expand="true"
                  style="width: 500px"

                  filterable
                  show-all-levels
                  multiple
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="35">
          <el-col :span="24"  class="mb20">
            <el-form-item label="应用使用人群" prop="appSuitCrowds">
              <el-select v-model="state.ruleForm.appSuitCrowds" placeholder="请选择应用使用人群"
                         multiple clearable >
                <el-option
                    v-for="item in state.appSuitCrowdOptions"
                    :key="item.key"
                    :label="item.label"
                    :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="35">
          <el-col :span="24" class="mb20">
            <el-form-item label="应用终端类型" prop="appTerminal">
              <el-select v-model="state.ruleForm.appTerminal"
                         placeholder="请选择应用终端类型"
                         multiple
                         clearable
                         class="w100"
                         @change="appTerminalChange"
                         @clear="appTerminalClear">
                <el-option
                    v-for="item in state.appTerminalOptions"
                    :key="item.key"
                    :label="item.label"
                    :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="35">

          <el-col :span="24" class="mb20">
            <el-form-item label="应用分类" prop="appCategory">
              <el-select v-model="state.ruleForm.appCategory"
                         placeholder="请选择应用分类"
                         clearable
                         class="w100" style="width: 500px">
                <el-option
                    v-for="item in state.appCategoryOptions"
                    :key="item.key"
                    :label="item.label"
                    :value="item.value"
                    style="width: 500px"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

        </el-row>

        <el-row :gutter="35">
          <el-col :span="24" class="mb20">
            <el-form-item label="SDK可用接口" prop="interfaceIdList">
              <el-select v-model="state.ruleForm.interfaceIdList"
                         placeholder="请选择SDK可用接口"
                         multiple
                         clearable
                         class="w100" style="width: 500px">
                <el-option
                    v-for="item in state.interfaceOptions"
                    :key="item.key"
                    :label="item.label"
                    :value="item.value"
                    style="width: 500px"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="35">
          <el-col :span="24" class="mb20">
            <el-form-item label="是否需要登录" prop="needLogin">
              <el-select v-model="state.ruleForm.needLogin"
                         placeholder="请选择是否需要登录"
                         clearable
                         class="w100">
                <el-option
                    v-for="item in state.needLoginOptions"
                    :key="item.key"
                    :label="item.label"
                    :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="35">
          <el-col :span="24" class="mb20" v-show="state.visible.isWebShow">
            <el-form-item label="应用主页url地址" prop="appConfigHomePage">
              <el-input v-model="state.ruleForm.appConfigHomePage"
                        placeholder="请输入应用主页url地址"
                        clearable>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="35" v-show="state.visible.isMiniProgramShow">
          <el-col :span="24" class="mb20">
            <el-form-item label="小程序链接" prop="appConfigMiniProgramPage">
              <el-input v-model="state.ruleForm.appConfigMiniProgramPage"
                        placeholder="请输入小程序链接"
                        clearable>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="35" v-show="state.visible.isH5Show">
          <el-col :span="24" class="mb20">
            <el-form-item label="H5链接" prop="appConfigH5Page">
              <el-input v-model="state.ruleForm.appConfigH5Page"
                        placeholder="请输入小程序链接"
                        clearable>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="35">
          <el-col :span="24" class="mb20">
            <el-form-item label="网页授权回调地址" prop="appConfigAuthorizeRedirectUrl">
              <el-input v-model="state.ruleForm.appConfigAuthorizeRedirectUrl"
                        placeholder="请输入网页授权回调地址"
                        clearable>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="35">
          <el-col :span="24" class="mb20">
            <el-form-item label="消息推送地址" prop="appConfigEventNotifyUrl">
              <el-input v-model="state.ruleForm.appConfigEventNotifyUrl"
                        placeholder="请输入消息推送地址"
                        clearable>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="35">
          <el-col :span="24" class="mb20">
            <el-form-item label="排序序号" prop="priorityNum">
              <el-input-number v-model="state.ruleForm.priorityNum" :min="1"/>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel" size="default">取 消</el-button>
					<el-button type="primary" @click="onSubmit(appsDialogFormRef)" size="default">{{
              state.dialog.submitTxt
            }}</el-button>
				</span>
      </template>
    </el-dialog>

    <el-dialog v-model="dialogVisible">
      <img w-full h-full style="width: 100%;height: 100%" :src="dialogImageUrl" alt="Preview Image"/>
    </el-dialog>

  </div>
</template>

<script setup lang="ts" name="appsDialog">
import {nextTick, onMounted, reactive, ref} from 'vue';
import {Plus} from '@element-plus/icons-vue'
import type {FormRules, UploadProps, FormInstance} from 'element-plus'
import {ElMessage, UploadUserFile} from "element-plus";

import {useAppsApi} from "/@/api/apps";

const {add, edit} = useAppsApi();
// 定义变量内容
const appsDialogFormRef = ref<FormInstance>();
const state = reactive({
  visible: {
    isWebShow: false,
    isH5Show: false,
    isMiniProgramShow: false,
  },
  // 学校org树数据
  sysOrgData: [] as OrgTreeType[],
  // 区域org树数据
  areaOrgData: [] as OrgTreeType[],
  // 可用接口选择
  interfaceOptions: [],
  ruleForm: {
    id: '',
    orgId: '',
    areaOrgIds: '',
    accountId: '',
    comId: '',
    devId: '',
    appId: '',
    appName: '',
    appShortName: '',
    appShortDesc: '',
    appLogo: '',
    appCategory: '',
    appSuitCrowds: [],
    appApplyLevel: '',
    appPayType: '',
    appChargeCycle: '',
    appTerminal: [],
    appStatus: '',
    appConfigHomePage: '',
    appConfigMiniProgramPage: '',
    appConfigH5Page: '',
    appConfigAuthorizeRedirectUrl: '',
    appConfigEventNotifyUrl: '',
    reviewUserId: '',
    reviewStatus: '',
    reviewMessage: '',
    viewNum: '',
    evaluateStar: '',
    priorityNum: '',
    needLogin: '',
    isDelete: '',
    interfaceIdList: []
  },
  dialog: {
    isShowDialog: false,
    type: '',
    title: '',
    submitTxt: '',
  },
  appSuitCrowdOptions: [
    // {value: '0', key: '0', label: '不限'},
    {value: 'student', key: '1', label: '学生'},
    {value: 'teacher', key: '2', label: '普通教师'},
    {value: 'teacherManager', key: '3', label: '教师管理员'},
    {value: 'parent', key: '4', label: '家长'},
    {value: 'leader', key: '5', label: '教育局管理员'},
    {value: 'schoolManager', key: '6', label: '学校管理员'},
    {value: 'BOELeader', key: '7', label: 'BOE-教育局领导'},
    {value: 'BOEDepartmentHead', key: '8', label: 'BOE-部门负责人'},
    {value: 'BOEDepartmentStaff', key: '9', label: 'BOE-部门工作人员'},
    {value: 'BOESchoolHead', key: '10', label: 'BOE-校长'},
    {value: 'BOESchoolDirector', key: '11', label: 'BOE-办公室主任'},
  ],
  appTerminalOptions: [
    {value: '1', key: '1', label: 'web端'},
    {value: '2', key: '2', label: '小程序'},
    {value: '3', key: '3', label: 'H5'},
  ],
  appCategoryOptions: [
    {value: '1', key: '1', label: '教育教学'},
    {value: '2', key: '2', label: '教育管理'},
    {value: '3', key: '3', label: '教育评价'},
    {value: '4', key: '4', label: '教育服务'},
  ],
  needLoginOptions: [
    {value: '1', key: '1', label: '是'},
    {value: '0', key: '0', label: '否'},
  ],
  sysOrgTreeData: {
    data: [],
    total: 0,
    loading: false,
    param: {
      pageNum: 1,
      pageSize: 2100,
    },
  },
});
const fileList = ref<UploadUserFile[]>([])
const imageUrl = ref('')
const dialogImageUrl = ref('')
const dialogVisible = ref(false)

// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);
const props = defineProps(['orgTree', 'areaOrgTree', 'interfaceOptions'])

const rules = reactive<FormRules<RowAppsType>>({
  appName: [
    {required: true, message: '应用名称不能为空', trigger: 'blur'},
    {min: 3, max: 10, message: '应用名称长度应该在3到10个字符之间', trigger: 'blur'},
  ],
  appShortName: [
    {required: true, message: '应用简称不能为空', trigger: 'blur'},
    {min: 3, max: 20, message: '应用简称长度,至少3个字符，最多20个字符', trigger: 'blur'},
  ],
  appShortDesc: [
    {required: true, message: '应用描述不能为空', trigger: 'blur'},
    {min: 3, max: 50, message: '应用描述长度,至少3个字符，最多50个字符', trigger: 'blur'},
  ],
  appLogo: [
    {required: true, message: '必须上传应用logo', trigger: 'blur'},
  ],
  orgId: [
    {type: 'array', required: true, message: '请在所属机构中至少选择一项，可多选'},
  ],
  appSuitCrowds: [
    {type: 'array', required: true, message: '请在适用人群中至少选择一项，可多选'},
  ],
  interfaceIdList:  [
    {type: 'array', required: true, message: '请在适用人群中至少选择一项，可多选'},
  ],
  appTerminal: [
    {required: true, message: '请选择应用终端类型', trigger: 'change'},
  ],
  appCategory: [
    {required: true, message: '请选择应用分类', trigger: 'change'},
  ],
  needLogin: [
    {required: true, message: '请选择是否需要登录', trigger: 'change'},
  ],
  // appConfigHomePage: [
  //   {required: false, message: '请填写web端应用主页', trigger: 'blur'},
  // ],
  // appConfigMiniProgramPage: [
  //   {required: false, message: '请填写小程序链接', trigger: 'blur'},
  // ],
  // appConfigH5Page: [
  //   {required: false, message: '请填写H5链接', trigger: 'blur'},
  // ],
  // appConfigAuthorizeRedirectUrl: [
  //   {required: true, message: '请填写授权地址', trigger: 'blur'},
  // ],
  appConfigEventNotifyUrl: [
    {required: true, message: '请填写消息推送地址', trigger: 'blur'},
  ]
})

const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw!)
  state.ruleForm.appLogo = response.data
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {

  if (fileList.value.length === 1) {
    ElMessage.error('只能上传一张图片!')
    return false
  }

  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('必须为png或jpeg格式的图片!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小不能超过2MB!')
    return false
  }
  return true
}

const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles)
}

const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}

// 打开弹窗
const openDialog = async (type: string, row: RowAppsType) => {
  state.sysOrgData = props.orgTree;
  state.areaOrgData = props.areaOrgTree;
  state.interfaceOptions = props.interfaceOptions;
  if (type === 'edit') {
    state.dialog.title = '修改应用信息';
    state.dialog.submitTxt = '修 改';
    state.ruleForm = row;
    fileList.value = [];
    fileList.value.push({name: row.appLogo, url: row.appLogo})
    checkAppTerminalForUpdate(state.ruleForm.appTerminal, row)
  } else {
    state.dialog.title = '创建应用';
    state.dialog.submitTxt = '新 增';
    fileList.value = [];
    state.ruleForm = {
      id: '',
      orgId: '',
      areaOrgIds: '',
      accountId: '',
      comId: '',
      devId: '',
      appId: '',
      appName: '',
      appShortName: '',
      appShortDesc: '',
      appLogo: '',
      appSuitCrowds: [],
      appApplyLevel: '',
      appPayType: '',
      appChargeCycle: '',
      appTerminal: [],
      appStatus: '',
      appConfigHomePage: '',
      appConfigMiniProgramPage: '',
      appConfigH5Page: '',
      appConfigAuthorizeRedirectUrl: '',
      appConfigEventNotifyUrl: '',
      reviewUserId: '',
      reviewStatus: '',
      reviewMessage: '',
      viewNum: '',
      evaluateStar: '',
      isDelete: '',
    }
    clearAppTerminal();
    // await nextTick(() => {
    //   if (appsDialogFormRef.value) {
    //     appsDialogFormRef.value.resetFields();
    //   }
    // });
  }
  state.dialog.isShowDialog = true;
};
// 关闭弹窗
const closeDialog = () => {
  state.dialog.isShowDialog = false;
};
// 取消
const onCancel = () => {
  closeDialog();
};
// 提交
const onSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (!valid) {
      console.log('error submit!!', fields);
      ElMessage.error('数据校验失败!');
      return false;
    }
    const res = state.ruleForm.id ? await edit(state.ruleForm) : await add(state.ruleForm)
    if (res.status === 200) {
      ElMessage.success(state.ruleForm.id ? '更改成功' : '新增成功');
    }
    closeDialog();
    emit('refresh');
  });

  // if (state.dialog.type === 'add') { }
};

const clearAppTerminal = () => {
  state.visible.isWebShow = false
  state.ruleForm.appConfigHomePage = ''
  state.visible.isMiniProgramShow = false
  state.ruleForm.appConfigMiniProgramPage = ''
  state.visible.isH5Show = false
  state.ruleForm.appConfigH5Page = ''
  rules.appConfigHomePage = [
    {required: false, message: '请填写web端应用主页', trigger: 'blur'}
  ]
  rules.appConfigMiniProgramPage = [
    {required: false, message: '请填写小程序链接', trigger: 'blur'}
  ]
  rules.appConfigH5Page = [
    {required: false, message: '请填写H5链接', trigger: 'blur'}
  ]
}

const checkAppTerminalForUpdate = (value: any, row: RowAppsType) => {
  if (value.includes('1')) {
    state.ruleForm.appConfigHomePage = row.appConfigHomePage;
    state.visible.isWebShow = true
    rules.appConfigHomePage = [
      {required: true, message: '请填写web端应用主页', trigger: 'blur'}
    ]
  } else {
    state.ruleForm.appConfigHomePage = ''
    state.visible.isWebShow = false
    rules.appConfigHomePage = [
      {required: false, message: '请填写web端应用主页', trigger: 'blur'}
    ]
  }
  if (value.includes('2')) {
    state.ruleForm.appConfigMiniProgramPage = row.appConfigMiniProgramPage;
    state.visible.isMiniProgramShow = true
    rules.appConfigMiniProgramPage = [
      {required: true, message: '请填写小程序链接', trigger: 'blur'}
    ]
  } else {
    state.ruleForm.appConfigMiniProgramPage = ''
    state.visible.isMiniProgramShow = false
    rules.appConfigMiniProgramPage = [
      {required: false, message: '请填写小程序链接', trigger: 'blur'}
    ]
  }
  if (value.includes('3')) {
    state.ruleForm.appConfigH5Page = row.appConfigH5Page;
    state.visible.isH5Show = true
    rules.appConfigH5Page = [
      {required: true, message: '请填写H5链接', trigger: 'blur'}
    ]
  } else {
    state.ruleForm.appConfigH5Page = ''
    state.visible.isH5Show = false
    rules.appConfigH5Page = [
      {required: false, message: '请填写H5链接', trigger: 'blur'}
    ]
  }
}

const checkAppTerminal = (value: any) => {
  if (value.includes('1')) {
    state.visible.isWebShow = true
    rules.appConfigHomePage = [
      {required: true, message: '请填写web端应用主页', trigger: 'blur'}
    ]
  } else {
    state.ruleForm.appConfigHomePage = ''
    state.visible.isWebShow = false
    rules.appConfigHomePage = [
      {required: false, message: '请填写web端应用主页', trigger: 'blur'}
    ]
  }
  if (value.includes('2')) {
    state.visible.isMiniProgramShow = true
    rules.appConfigMiniProgramPage = [
      {required: true, message: '请填写小程序链接', trigger: 'blur'}
    ]
  } else {
    state.ruleForm.appConfigMiniProgramPage = ''
    state.visible.isMiniProgramShow = false
    rules.appConfigMiniProgramPage = [
      {required: false, message: '请填写小程序链接', trigger: 'blur'}
    ]
  }
  if (value.includes('3')) {
    state.visible.isH5Show = true
    rules.appConfigH5Page = [
      {required: true, message: '请填写H5链接', trigger: 'blur'}
    ]
  } else {
    state.ruleForm.appConfigH5Page = ''
    state.visible.isH5Show = false
    rules.appConfigH5Page = [
      {required: false, message: '请填写H5链接', trigger: 'blur'}
    ]
  }
}

const appTerminalChange = (value: any) => {
  console.log(value)
  if (value.length === 0) {
    clearAppTerminal();
  } else {
    checkAppTerminal(value)
  }
}
const appTerminalClear = () => {
  console.log('清空')
}

onMounted(() => {

})

// 暴露变量
defineExpose({
  openDialog,
});
</script>
<style scoped lang="scss">
.croppers-container {
  .cropper-img-warp {
    text-align: center;

    .cropper-img {
      margin: auto;
      width: 150px;
      height: 150px;
      border-radius: 100%;
    }
  }
}
</style>
